<template>
  <div class="websocket-status">
    <el-tag 
      :type="isConnected ? 'success' : 'danger'"
      size="small"
    >
      <el-icon v-if="isConnected"><CircleCheck /></el-icon>
      <el-icon v-else><CircleClose /></el-icon>
      {{ isConnected ? 'WebSocket已连接' : 'WebSocket未连接' }}
    </el-tag>
  </div>
</template>

<script setup lang="ts">
import {
  onMounted,
  onUnmounted,
  ref,
} from 'vue'

import $bus from '@/mitt'
import wsManager from '@/utils/websocket'
import {
  CircleCheck,
  CircleClose,
} from '@element-plus/icons-vue'

const isConnected = ref(false)

// 检查连接状态
const checkConnectionStatus = () => {
  isConnected.value = wsManager.isConnected()
}

// 监听连接状态变化
const handleConnectionChange = () => {
  checkConnectionStatus()
}

onMounted(() => {
  // 初始检查
  checkConnectionStatus()
  
  // 监听连接状态变化
  $bus.on('websocket-connected', handleConnectionChange)
  $bus.on('websocket-disconnected', handleConnectionChange)
  
  // 定期检查连接状态
  const interval = setInterval(checkConnectionStatus, 5000)
  
  onUnmounted(() => {
    clearInterval(interval)
    $bus.off('websocket-connected', handleConnectionChange)
    $bus.off('websocket-disconnected', handleConnectionChange)
  })
})
</script>

<style scoped lang="scss">
.websocket-status {
  display: flex;
  align-items: center;
  gap: 4px;
}
</style> 